<template>
  <div class="collection-container">
    <!-- 头部背景 -->
    <div class="header-background"></div>
    
    <!-- 主要内容 -->
    <div class="content-wrapper">
      <!-- 头部标题 -->
      <div class="collection-header">
        <h1>我的收藏馆</h1>
        <div class="collection-stats">
          <div class="stat-card">
            <div class="stat-icon total">
              <el-icon><Collection /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ collectionStats.total }}</div>
              <div class="stat-label">宝藏总数</div>
            </div>
          </div>
          
          <div class="stat-card">
            <div class="stat-icon rare">
              <el-icon><Star /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ collectionStats.rare }}</div>
              <div class="stat-label">稀有宝藏</div>
            </div>
          </div>
          
          <div class="stat-card">
            <div class="stat-icon legendary">
              <el-icon><Trophy /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ collectionStats.legendary }}</div>
              <div class="stat-label">传说宝藏</div>
            </div>
          </div>
          
          <div class="stat-card">
            <div class="stat-icon sets">
              <el-icon><Collection /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ collectionStats.sets }}</div>
              <div class="stat-label">完整系列</div>
            </div>
          </div>
        </div>
      </div>

      <!-- 收藏进度和奖励 -->
      <el-card class="progress-card">
        <template #header>
          <div class="card-header">
            <span>收藏进度</span>
            <el-tooltip content="集齐特定数量的宝藏可获得额外奖励">
              <el-icon><InfoFilled /></el-icon>
            </el-tooltip>
          </div>
        </template>
        
        <div class="collection-progress">
          <div class="progress-levels">
            <div 
              v-for="(reward, index) in rewards" 
              :key="index"
              class="reward-level"
              :class="{ 'achieved': collectionStats.total >= reward.requirement }"
            >
              <div class="reward-icon" :class="{ 'glow': collectionStats.total >= reward.requirement }">
                <el-icon v-if="collectionStats.total >= reward.requirement"><Check /></el-icon>
                <el-icon v-else><Lock /></el-icon>
              </div>
              <div class="reward-line" :class="{ 'achieved': collectionStats.total >= reward.requirement }"></div>
              <div class="reward-info">
                <div class="reward-title">{{ reward.title }}</div>
                <div class="reward-requirement">收集 {{ reward.requirement }} 个宝藏</div>
                <el-button 
                  size="small" 
                  :type="collectionStats.total >= reward.requirement ? 'success' : 'info'"
                  :disabled="collectionStats.total < reward.requirement"
                  @click="claimReward(reward)"
                >
                <span v-if="collectionStats.total >= reward.requirement && reward.claimed">已领取</span>
                <span v-else-if="collectionStats.total >= reward.requirement && !reward.claimed">领取奖励</span>
                <span v-else>未解锁</span>
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </el-card>

      <!-- 宝藏系列 -->
      <el-card class="series-card">
        <template #header>
          <div class="card-header">
            <span>宝藏系列</span>
            <div class="series-filters">
              <el-select v-model="filters.series" placeholder="全部系列" clearable>
                <el-option
                  v-for="item in seriesOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
              <el-select v-model="filters.rarity" placeholder="全部稀有度" clearable>
                <el-option
                  v-for="item in rarityOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
              <el-input
                v-model="filters.search"
                placeholder="搜索宝藏"
                clearable
                class="search-input"
              >
                <template #prefix>
                  <el-icon><Search /></el-icon>
                </template>
              </el-input>
            </div>
          </div>
        </template>

        <!-- 系列展示 -->
        <div v-for="series in filteredSeries" :key="series.id" class="treasure-series">
          <div class="series-info">
            <h3>{{ series.name }} <span class="series-progress">{{ series.collected > series.total? series.total:series.collected }}/{{ series.total }}</span></h3>
            <el-progress 
              :percentage="Number(((series.collected / series.total) * 100).toFixed(0))" 
              :status="series.collected >= series.total ? 'success' : ''"
              :stroke-width="10"
            />
            <div v-if="series.collected >= series.total" class="series-complete">
              <el-tag type="success">系列完成</el-tag>
              <el-tooltip :content="rewardTooltipContent(series)" >
                <el-button type="success" size="small" plain circle @click="claimRewardSeries(series.id, series.reward)">
                  <el-icon><Present /></el-icon>
                </el-button>
              </el-tooltip>
            </div>
          </div>

          <!-- 宝藏网格 -->
          <div class="treasure-grid">
            <div 
              v-for="treasure in series.treasures" 
              :key="treasure.id"
              class="treasure-card"
              :class="{ 'owned': treasure.owned, [treasure.rarity]: true }"
            >
              <div class="treasure-image">
                <img :src="treasure.image" :alt="treasure.name" />
                <div v-if="treasure.owned" class="owned-badge">
                  <el-icon><Check /></el-icon>
                </div>
                <div v-else class="lock-icon">
                  <el-icon><Lock /></el-icon>
                </div>
              </div>
              <div class="treasure-info">
                <h4>{{ treasure.name }}</h4>
                <div class="treasure-rarity">
                  <el-tag :type="rarityType(treasure.rarity)" size="small">{{ treasure.rarity }}</el-tag>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 空状态 -->
        <el-empty
          v-if="filteredSeries.length === 0"
          description="没有找到匹配的宝藏"
        >
          <el-button @click="resetFilters">重置筛选</el-button>
        </el-empty>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { 
  Check, 
  Lock, 
  Search, 
  InfoFilled, 
  Present,
  Trophy,
  Star,
  Collection
} from '@element-plus/icons-vue';

import { useWalletStore } from '@/stores/walletStore';
import '@/styles/CollectionView.css';
import { ethers } from 'ethers';
const walletStore = useWalletStore();

// 收藏统计
const collectionStats = ref({
  total: 0,
  rare: 0,
  legendary: 0,
  sets: 0
});
let claimed5 = ref(false);
let claimed15 = ref(false);
let claimed30 = ref(false);
let claimed50 = ref(false);

// 奖励等级
const rewards = ref([
  { 
    title: '初级收藏家', 
    requirement: 5, 
    reward: '10 TRES 代币',
    claimed: claimed5
  },
  { 
    title: '中级收藏家', 
    requirement: 15, 
    reward: '30 TRES 代币',
    claimed: claimed15
  },
  { 
    title: '高级收藏家', 
    requirement: 30, 
    reward: '100 TRES 代币',
    claimed: claimed30
  },
  { 
    title: '传奇收藏家', 
    requirement: 50, 
    reward: '100 TRES 代币',
    claimed: claimed50
  }
]);
async function getClaimed(index){
  claimed5 = await walletStore.contract.hasClaimedReward5(walletStore.walletAddress);
  claimed15 = await walletStore.contract.hasClaimedReward15(walletStore.walletAddress);
  claimed30 = await walletStore.contract.hasClaimedReward30(walletStore.walletAddress);
  claimed50 = await walletStore.contract.hasClaimedReward50(walletStore.walletAddress);
  rewards.value[0].claimed = claimed5;
  rewards.value[1].claimed = claimed15;
  rewards.value[2].claimed = claimed30;
  rewards.value[3].claimed = claimed50;
  console.log("领取奖励:",claimed5,claimed15,claimed30,claimed50);
}
// 筛选条件
const filters = ref({
  series: '',
  rarity: '',
  search: ''
});

// 系列选项
const seriesOptions = ref([
  { value: 'forest', label: '森林系列' },
  { value: 'ocean', label: '海洋系列' },
  { value: 'mountain', label: '山地系列' },
  { value: 'desert', label: '沙漠系列' },
]);

// 稀有度选项
const rarityOptions = ref([
  { value: 'common', label: '普通' },
  { value: 'rare', label: '稀有' },
  { value: 'epic', label: '史诗' },
  { value: 'legendary', label: '传说' }
]);

// 宝藏系列数据
const treasureSeries = ref([]);

// 获取宝藏系列数据
const fetchTreasureSeries = async () => {
  try {
    // 从智能合约获取各个系列的收集进度
    const [forest, ocean, mountain, desert] = await walletStore.collectionContract.getCollectionProgress(walletStore.walletAddress);
    // 获取玩家拥有的所有NFT
    const nftCount = await walletStore.contract.balanceOf(walletStore.walletAddress);
    const ownedTokenIds = await walletStore.contract.getOwnedNFTs(walletStore.walletAddress);
    
    // 获取每个NFT的详细信息
    const ownedNFTs = [];
    for (let i = 0; i < nftCount; i++) {
      const tokenId = ownedTokenIds[i];
      const uri = await walletStore.contract.tokenURI(tokenId);
      const response = await fetch(uri);
      const metadata = await response.json();
      const collection = await walletStore.collectionContract.getNFTCollection(tokenId); 
      console.log("collection:",collection);
      ownedNFTs.push({
        tokenId: tokenId.toString(),
        name: metadata.name,
        rarity: metadata.attributes[0].value.toLowerCase(),
        image: metadata.image ? `https://pink-obliged-bat-235.mypinata.cloud/ipfs/${metadata.image.slice(7)}` : '',
        collection: seriesOptions.value[collection].value, // 假设第二个属性是收藏集
        owned: true
      });
    }
    
    // 构建系列数据
    treasureSeries.value = [
      {
        id: 'Forest',
        name: '森林系列',
        collected: Number(forest),
        total: 5,
        treasures: ownedNFTs.filter(nft => nft.collection === 'forest'),
        reward: 50,
      },
      {
        id: 'Ocean',
        name: '海洋系列',
        collected: Number(ocean),
        total: 4,
        treasures: ownedNFTs.filter(nft => nft.collection === 'ocean'),
        reward: 70,
      },
      {
        id: 'Mountain',
        name: '山地系列',
        collected: Number(mountain),
        total: 6,
        treasures: ownedNFTs.filter(nft => nft.collection === 'mountain'),
        reward: 90,

      },
      {
        id: 'Desert',
        name: '沙漠系列',
        collected: Number(desert),
        total: 5,
        treasures: ownedNFTs.filter(nft => nft.collection === 'desert'),
        reward: 100,
      }
    ];

    // 统计收藏数据
    updateCollectionStats();
  } catch (error) {
    console.error('获取宝藏数据失败:', error);
    ElMessage.error('获取宝藏数据失败');
  }
};

// 更新收藏统计
const updateCollectionStats = () => {
  let total = 0;
  let rare = 0;
  let legendary = 0;
  let sets = 0;

  treasureSeries.value.forEach(series => {
    series.treasures.forEach(treasure => {
      if (treasure.owned) {
        total++;
        if (treasure.rarity === 'rare' || treasure.rarity === 'epic') {
          rare++;
        }
        if (treasure.rarity === 'legendary') {
          legendary++;
        }
      }
    });

    if (series.collected === series.total) {
      sets++;
    }
    
  });
  //updateTreasureData();
  collectionStats.value = { total, rare, legendary, sets };
};
const seriesEnum = {
  Desert: 3,
  Mountain: 2,
  Ocean: 1,
  Forest: 0,
}
// 领取系列奖励
const claimRewardSeries =async (seriesId, reward) => {
  try{
    console.log("领取系列奖励:",seriesId);
    console.log("奖励为：",seriesEnum[seriesId])
    const tx = await walletStore.collectionContract.claimCollectionReward(seriesEnum[seriesId]);
    ElMessage.success(`成功领取奖励: ${reward}`);
  }catch(error){
    if (error.message.includes("Already claimed")) {
      ElMessage.warning("奖励已领取过！");
    } else {
      console.log("领取奖励失败:", error);
      ElMessage.error("领取奖励失败！");
    }
  }
  
}

    

// 根据稀有度返回标签类型
const rarityType = (rarity) => {
  switch (rarity) {
    case 'common': return 'info';
    case 'rare': return 'primary';
    case 'epic': return 'warning';
    case 'legendary': return 'danger';
    default: return 'info';
  }
};

// 筛选系列
const filteredSeries = computed(() => {
  return treasureSeries.value.filter(series => {
    // 系列筛选
    if (filters.value.series && series.id !== filters.value.series) {
      return false;
    }

    // 搜索筛选
    if (filters.value.search) {
      const searchTerm = filters.value.search.toLowerCase();
      const hasTreasureMatch = series.treasures.some(t => 
        t.name.toLowerCase().includes(searchTerm)
      );
      const hasSeriesMatch = series.name.toLowerCase().includes(searchTerm);
      if (!hasTreasureMatch && !hasSeriesMatch) {
        return false;
      }
    }

    // 稀有度筛选
    if (filters.value.rarity) {
      const hasTreasureWithRarity = series.treasures.some(t => 
        t.rarity === filters.value.rarity
      );
      if (!hasTreasureWithRarity) {
        return false;
      }
    }

    return true;
  });
});

// 重置筛选条件
const resetFilters = () => {
  filters.value = {
    series: '',
    rarity: '',
    search: ''
  };
};

// 领取奖励
const claimReward = async (reward) => {
  try {
    let [total, ...claimStatus] = await walletStore.contract.getCollectionStatus(walletStore.walletAddress);
    rewards.value.forEach((reward, index) => {
      reward.claimed = claimStatus[index];
    });
    console.log("查看是否领取过:",rewards.value);
    console.log("领取奖励条件，达到:",reward.requirement,"个宝藏");
    const milestone = ethers.BigNumber.from(reward.requirement);
    console.log("里程碑:",milestone);
    // 调用智能合约领取奖励
    const result = await walletStore.contract.claimCollectionReward(milestone);
    console.log(result);
    ElMessage.success(`成功领取奖励: ${reward.reward}`);
    [total, ...claimStatus] = await walletStore.contract.getCollectionStatus(walletStore.walletAddress);
    rewards.value.forEach((reward, index) => {
      reward.claimed = claimStatus[index];
    });
    console.log("领取奖励后:",rewards.value);
    
  } catch (error) {
    console.error('领取奖励失败:', error);
    ElMessage.error('领取奖励失败');
  }
};

// 页面加载时获取数据
onMounted(() => {
  fetchTreasureSeries();
  getClaimed();
});
const rewardTooltipContent = (series) => {
  return `获得系列奖励：奖励 ${series.reward} 代币`;
};
</script>

<style scoped>


</style>
